package com.rjs.serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.Unmarshaller;

public class MarshallingSerializer implements ISerializer {

	final static MarshallingConfiguration configuration = new MarshallingConfiguration();
	final static MarshallerFactory marshallerFactory =  Marshalling.getProvidedMarshallerFactory("serial");
	
	static {
		configuration.setVersion(5);
	}
	
	public <T> byte[] serialize(T obj) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		Marshaller marshaller = marshallerFactory.createMarshaller(configuration);
		marshaller.start(Marshalling.createByteOutput(byteArrayOutputStream));
		marshaller.writeObject(obj);
		marshaller.finish();
		return byteArrayOutputStream.toByteArray();
	}

	@SuppressWarnings("unchecked")
	public <T> T deserialize(byte[] buf, Class<T> clzz) throws IOException, ClassNotFoundException {
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buf);
		Unmarshaller unmarshaller = marshallerFactory.createUnmarshaller(configuration);
		unmarshaller.start(Marshalling.createByteInput(byteArrayInputStream));
		Object object = unmarshaller.readObject();
		unmarshaller.finish();
		return (T)object;
	}

}
